<?php

use Buchin\GoogleSuggest\GoogleSuggest;

function salesea_create_keywords_list_txt_on_init(){
	$handle = fopen(__DIR__."/data/suijifenlei.txt", "a");
	fclose($handle);
	$categories = get_categories( [ 'hide_empty' => false ]);
	foreach ( $categories as $category){
		$categoryid = $category->cat_ID;
		$file = fopen(__DIR__."/data/keywords_cat$categoryid.txt", "a");
		fclose($file);
	}
}

function salesea_get_category_list_and_return_fields(){

	    $categories = get_categories( [ 'hide_empty' => false ]);

	    $wenda = get_option('wenda');

		if($wenda === false){
			$suijifenlei_number = 0;
		}else{
			$suijifenlei = $wenda['suijifenlei'];
			if(!empty($suijifenlei)){
				$suijifenlei_number = count(explode(PHP_EOL, $suijifenlei));
			}else{
				$suijifenlei_number = 0;
			}
		}

		$fields_array = array(
			array(
				'id'    => 'suijifenlei',
				'type'  => 'textarea',
				'title' => "随机分类($suijifenlei_number)",
				'desc'  => '每次执行发布，随机一个分类发布一篇文章，在上面填入关键词一行一个'
			)
		);

		foreach ( $categories as $category ) {
			$name = $category->name;
			$categoryid = $category->cat_ID;

			if($wenda === false){
				$fenleineirong_number = 0;
			}else{
				$fenleineirong = $wenda["keywords_cat$categoryid"];
				if(!empty($fenleineirong)){
					$fenleineirong_number = count(explode(PHP_EOL, $fenleineirong));
				}else{
					$fenleineirong_number = 0;
				}
			}

			$fields_array[] = array(
				'id'    => 'keywords_cat' . $categoryid,
				'type'  => 'textarea',
				'title' => $name."($fenleineirong_number)",
				'desc'  => "当前分类是$name,请输入关键词，一行一个"
			);
		}

		return $fields_array;

}

function filter_escape( $string ) {
	$values = array(
		'&quot;',
		'&amp;',
		'&lt;',
		'&gt;',
		'&nbsp;',
		'&quot',
		'&amp',
		'&lt',
		'&gt',
		'&nbsp',
		';;',
		'&?',
		'?&',
	);

	return str_replace( $values, '', $string );
}

function salesea_get_mmps() {
	$filename = __DIR__ . '/assets/mmp.txt';

	if ( ! is_file( $filename ) ) {
		return array();
	}
	$string = str_replace( "\r", '', file_get_contents( $filename ) );

	return array_values( array_unique( array_filter( explode( "\n", $string ) ) ) );
}

function salesea_to_utf8( $content ) {
	$encode = mb_detect_encoding( $content, [ 'ASCII', 'GB2312', 'GBK', 'UTF-8', 'EUC-CN', 'CP936' ] );

	if ( 'UTF-8' != $encode ) {
		return @iconv( $encode, 'UTF-8//IGNORE', $content );
	}

	return $content;
}

function salesea_is_utf8( $content ) {
	$encode = mb_detect_encoding( $content, [ 'ASCII', 'GB2312', 'GBK', 'UTF-8', 'EUC-CN', 'CP936' ] );

	return 'UTF-8' == $encode;
}

function salesea_valid_keyword( $keyword ) {
	foreach ( salesea_get_mmps() as $mmp ) {
		if ( false !== mb_strpos( $keyword, $mmp ) ) {
			return false;
		}
	}

	$rules = array(
		'/[\x{4e00}-\x{9fa5}]/u',
		'/[0-9]/',
		'/[a-z]/i',
	);

	$keyword = preg_replace( $rules, '', trim( $keyword ) );

	return ! ( mb_strlen( $keyword ) > 0 ); // 大于 0 就是包含了特殊字符，就不能要
}

function salesea_curl(
	$url,
	$headers = array(),
	$isPost = false,
	$timeout = 30,
	$isProxy = true,
	$toUtf8 = true,
	$postData = array()
) {
	try {

		$curl = curl_init();
		// 设置抓取的url
		curl_setopt( $curl, CURLOPT_URL, $url );
		// 设置头文件的信息作为数据流输出
		curl_setopt( $curl, CURLOPT_HEADER, 0 );
		// 超时设置,以秒为单位
		curl_setopt( $curl, CURLOPT_TIMEOUT, $timeout );
		// 设置请求头
		curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
		// 设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );

		curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt( $curl, CURLOPT_POST, $isPost );

		// Operation timed out after 30000 milliseconds with 0 bytes received !!!!
		curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, false );

		if ( ! empty( $postData ) ) {
			curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $postData ) );
		}

		if ( $response = curl_exec( $curl ) ) {
			curl_close( $curl );
			if ( $toUtf8 ) {
				return salesea_to_utf8( $response );
			} else {
				return $response;
			}
		}

		if ( $message = curl_error( $curl ) ) {
			throw new Exception( "get document error：$url => {$message}" );
		}
		curl_close( $curl );
	} catch ( Exception $e ) {
		// Just so so
	}

	if ( $toUtf8 ) {
		return salesea_to_utf8( $response );
	} else {
		return $response;
	}
}

function salesea_file_get( $url ) {
	$contextOptions = array(
		"ssl" => array(
			"verify_peer"      => false,
			"verify_peer_name" => false,
		),
	);

	// 必须 file_get_contents 因为 CURL 不知道为什么就会变成 PC
	return file_get_contents( $url, false, stream_context_create( $contextOptions ) );
}

function salesea_baiduxiala( $keyword ) {
	$encodeKeyword = urlencode( $keyword );

	$data = salesea_curl(
		"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd={$encodeKeyword}",
		array(),
		false,
		15,
		false
	);
	$data = str_replace( ');', '', $data );
	$data = str_replace( 'window.baidu.sug(', '', $data );
	$data = str_replace( 'q:', '"q":', $data );
	$data = str_replace( 'p:false', '"p":"false"', $data );
	$data = str_replace( 'p:true', '"p":"true"', $data );
	$data = str_replace( 's:', '"s":', $data );

	if ( ! salesea_is_utf8( $data ) ) {
		return array(); // 不是 utf8 不要
	}

	$data = json_decode( $data, true );

	if ( is_array( $data ) && isset( $data['s'] ) ) {
		$words = array();
		foreach ( $data['s'] as $datum ) {
			if ( salesea_valid_keyword( $datum ) ) {
				$words[] = trim( $datum );
			}
		}

		return $words;
	}

	return array();
}

function salesea_baiduxialaV2( $keyword ) {
	$encodeKeyword = urlencode( $keyword );

	$json = salesea_file_get(
		"https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd={$encodeKeyword}"
	);

	$data = json_decode( $json, true );
	$data = is_array( $data ) ? $data : array();
	$data = isset( $data['g'] ) ? $data['g'] : array();

	$words = array();
	foreach ( $data as $datum ) {
		if ( isset( $datum['q'] ) ) {
			$words[] = $datum['q'];
		}
	}

	return $words;
}

function salesea_xiala( $keyword ) {
	$keywords = salesea_baiduxialaV2( $keyword );

	if ( empty( $keywords ) ) {
		$keywords = salesea_baiduxiala( $keyword );
	}

	return $keywords;
}

function salesea_generate_title( $keyword ) {
	$relatedLists = salesea_xiala( $keyword );
	list( $title, $related ) = title_formatter( $keyword, $relatedLists );
	$title = diy_filter( $title );
	$seperators = ["– ","— ","• "," ","| ","_ "];
	$random_seperator = $seperators[array_rand($seperators)];

	if(_wenda("lianxiangcisousuoyinqing") === "谷歌"){
		$suggested = GoogleSuggest::grab($keyword);
		if(!empty($suggested)){
			$random_suggest = $suggested[array_rand($suggested)];
			$title = $random_suggest;
			$related = $random_suggest;
		}else{
			$title = $keyword;
			$related = '';
		}
	}else{
		if(empty($related)){
			$title = $keyword;
			$related = '';
		}else{
			$title = $keyword.$random_seperator.$related;
		}
	}

	return ["keyword" => $keyword, 'related' => $related, 'title' => $title];
}

function salesea_sanitize_permalink($permalink) {

	$permalink = trim( $permalink );

	// Remove special characters
	$permalink = preg_replace( '/[^A-Za-z0-9-]+/', '-', $permalink );

	// Remove double hyphens
	$permalink = preg_replace( '/--+/', '-', $permalink );

	// Convert spaces to hyphens
	$permalink = preg_replace( '/\s+/', '-', $permalink );

	return $permalink;
}

function salesea_insert_task_queue_or_insert_post(){

	$res = salesea_check_task_status_and_return_content();

	if ( $res === false ) {
		return false;
	} else {

		if(_wenda("fabuwenzhangzhuangtai") === "公开"){
			$post_status = "publish";
		}else{
			$post_status = "draft";
		}

		    $content = $res['content'];

		    $image_url = $res['image'];
			if(_wenda("tupiancharuzhengwen") === "文章顶部"){
				$content = "<img src=".$image_url.">".$res['content'];
			}

		$inserted = wp_insert_post( [
			'post_title'    => $res['title'],
			'post_content'  => $content,
			'post_status'   => $post_status,
			'post_author' => 1,
			'post_category' => [ $res['cat_id']],
			'post_name' => salesea_sanitize_permalink(str_replace(" ", "-", $res['title']))
		]);

		   if ($inserted){
			   $tags = explode( ',', $res['keyword']);
			   wp_set_post_terms( $inserted, $tags, 'post_tag', true);
			}
		}

	return [ 'inserted' => $inserted, 'keyword' => $res['keyword'] ];

}

function salesea_insert_image_url_as_post_thumbnail( $image_url, $post_id ) {
	if ( isset( $image_url ) ) {
		require_once( ABSPATH . 'wp-admin/includes/file.php' );
		require_once( ABSPATH . 'wp-admin/includes/media.php' );
		require_once( ABSPATH . 'wp-admin/includes/image.php' );

		$tmp = download_url( $image_url );

		if ( is_wp_error( $tmp ) ) {
			// handle error
			return $tmp->get_error_message();
		}

		$file_array = array(
			'name'     => basename( $image_url ),
			'tmp_name' => $tmp
		);

		$attachment_id = media_handle_sideload( $file_array, $post_id );

		// Set the featured image
		set_post_thumbnail( $post_id, $attachment_id );

		return true;
	} else {
		return false;
	}
}

function count_total_tasks() {
	global $wpdb;
	$table_name = $wpdb->prefix."salesea_tasks";
	$sql = "SELECT COUNT(id) FROM $table_name";
	$total_count = $wpdb->get_var( $sql );

	$total_completed_sql = "SELECT * FROM $table_name WHERE status = 2";
	$total_completed = $wpdb->get_results( $total_completed_sql );

	set_transient("total_tasks", $total_count);

	return $total_count;
}

function remove_salesea_keyword_and_update($keyword, $salesea_key){
	$wenda = get_option('wenda');
	$keywords_array = explode(PHP_EOL, _wenda($salesea_key));
	$index = array_search($keyword, $keywords_array);
	unset($keywords_array[$index]);
	$wenda[$salesea_key] = implode(PHP_EOL, $keywords_array);
	update_option("wenda", $wenda);
}

function salesea_insert_generated_thumbnail()
{
	$args = array(
		'post_type' => 'post',
		'posts_per_page' => 1,
		'orderby' => 'date',
		'order' => 'DESC'
	);

	$query = new WP_Query($args);

	if ($query->have_posts()) {
		$query->the_post();
		$title = get_the_title();
		$title = str_replace("\r", "", $title);
		$image_url = salesea_generate_image($title);
		if(_wenda('tupianzuotoutu')){
			salesea_insert_image_url_as_post_thumbnail($image_url,get_the_ID());
		}
	}

	wp_reset_postdata();
}



